<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="發票編碼" prop="invocieCode">
        <el-input
          v-model="queryParams.invocieCode"
          placeholder="請輸入發票編碼"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="標題" prop="invoiceTitle">
        <el-input
          v-model="queryParams.invoiceTitle"
          placeholder="請輸入標題"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="報價單編碼" prop="quoteCode">
        <el-input
          v-model="queryParams.quoteCode"
          placeholder="請輸入報價單編碼"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客戶編碼" prop="customerCode">
        <el-input
          v-model="queryParams.customerCode"
          placeholder="請輸入客戶編碼"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客戶名稱" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="請輸入客戶名稱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="發票狀態" prop="invoiceStatus">
        <el-select
          v-model="queryParams.invoiceStatus"
          placeholder="請選擇發票狀態"
          clearable
        >
          <el-option
            v-for="dict in dict.type.invoice_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="金額" prop="invoiceAmount">
        <el-input
          v-model="queryParams.invoiceAmount"
          placeholder="請輸入金額"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="金額(含稅)" prop="invoiceTaxAmount">
        <el-input
          v-model="queryParams.invoiceTaxAmount"
          placeholder="請輸入金額"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="稅金" prop="taxAmount">
        <el-input
          v-model="queryParams.taxAmount"
          placeholder="請輸入稅金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="付款時間" prop="payTime">
        <el-date-picker
          clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="請選擇付款時間"
        >
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="入賬銀行賬號" prop="inBankNo">
        <el-input
          v-model="queryParams.inBankNo"
          placeholder="請輸入入賬銀行賬號"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="入賬銀行名稱" prop="inBankName">
        <el-input
          v-model="queryParams.inBankName"
          placeholder="請輸入入賬銀行名稱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="入賬賬戶" prop="inBankAmount">
        <el-input
          v-model="queryParams.inBankAmount"
          placeholder="請輸入入賬賬戶"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="有效時間" prop="dueDate">
        <el-date-picker clearable
          v-model="queryParams.dueDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="請選擇到期日">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:invoice:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:invoice:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['biz:invoice:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['biz:invoice:export']"
          >導出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="invoiceList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        label="發票編碼"
        width="180"
        align="center"
        prop="invoiceCode"
      />
      <el-table-column label="標題" align="center" prop="invoiceTitle" />
      <el-table-column
        label="報價單編碼"
        width="180"
        align="center"
        prop="quoteCode"
      />
      <el-table-column
        label="客戶編碼"
        width="180"
        align="center"
        prop="customerCode"
      />
      <el-table-column label="客戶名稱" align="center" prop="customerName" />
      <el-table-column label="不含稅金額" align="center" prop="invoiceAmount" />
      <el-table-column label="含稅金額" align="center" prop="invoiceTaxAmount" />
      <el-table-column label="稅金" align="center" prop="taxAmount" />
      <el-table-column label="發票狀態" align="center" prop="invoiceStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.invoice_status"
            :value="scope.row.invoiceStatus"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="付款時間"
        align="center"
        prop="payTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.payTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="入賬銀行賬號"
        width="120"
        align="center"
        prop="inBankNo"
      />
      <el-table-column
        label="入賬銀行名稱"
        width="120"
        align="center"
        prop="inBankName"
      />
      <el-table-column label="入賬賬戶" align="center" prop="inBankAmount" />
      <el-table-column label="到期日" align="center" prop="dueDate" width="180">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.dueDate, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="備註" align="center" prop="remark" />
      <el-table-column
        width="220"
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:invoice:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['biz:invoice:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            >詳情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            :disabled="scope.row.invoiceStatus == 50||scope.row.invoiceStatus == 10"
            @click="handleCancel(scope.row)"
            v-hasPermi="['biz:invoice:cancel']"
            >撤回</el-button
          >
          <div>
            <el-button
              style="padding: 5px"
              size="mini"
              :disabled="scope.row.invoiceStatus != 30"
              type="primary"
              v-hasPermi="['biz:invoice:send']"
              @click="SendInvoice(scope.row)"
              >發送</el-button
            >
            <el-button
              style="padding: 5px"
              size="mini"
              type="primary"
              v-hasPermi="['biz:invoice:preview']"
              :disabled="scope.row.invoiceStatus == 10"
              @click="Download(scope.row)"
              >預覽</el-button
            >
            <el-button
              style="padding: 5px"
              size="mini"
              type="primary"
              v-hasPermi="['biz:invoice:collection']"
              :disabled="scope.row.invoiceStatus != 30"
              @click="payInvoice(scope.row)"
              >確認收款</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 確認收款款 -->
    <el-dialog :visible.sync="open_payInvoice" width="400px" append-to-body>
      <el-form
        ref="form_payInvoice"
        :model="form_payInvoice"
        :rules="rules_payInvoice"
        label-width="80px"
      >
        <el-form-item label="付款時間" prop="payTime">
          <el-date-picker
            clearable
            v-model="form_payInvoice.payTime"
            @input="$forceUpdate()"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="請選付款時間"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="submitForm_payInvoice"
          >確 定</el-button
        >
        <el-button @click="cancel_payInvoice">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  sendInvoice,
  payInvoice,
  cancelInvoice,
  downloadInvoice,
} from "@/api/biz/invoice";

export default {
  name: "Invoice",

  dicts: ["invoice_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中數組
      ids: [],
      // 子表选中數据
      checkedBizInvoiceItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 顯示搜索条件
      showSearch: true,
      // 总条數
      total: 0,
      // 發票單表格數据
      invoiceList: [],
      // 發票明細表格數据
      bizInvoiceItemList: [],
      // 弹出层標题
      title: "",
      // 是否顯示弹出层
      open: false,
      // 查询參數
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceTitle: null,
        invocieCode: null,
        quoteId: null,
        quoteCode: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        invoiceAmount: null,
        invoiceTaxAmount: null,
        taxAmount: null,
        invoiceStatus: null,
        payTime: null,
        inBankId: null,
        inBankNo: null,
        inBankName: null,
        inBankAmount: null,
        validMonth: null,
        dueDate: null,
        delFlag: null,
        orderByColumn: "update_time",
        isAsc: "desc",
      },
      // 表单參數
      form: {},
      open_payInvoice: false,
      form_payInvoice: {},
      // 表单校验
      rules: {
        invocieCode: [
          { required: true, message: "發票編碼不能為空", trigger: "blur" },
        ],
      },
      rules_payInvoice: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    SendInvoice(item) {
      sendInvoice(item.id).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("發送成功");
        }
      });
    },
    Download(item) {
      console.log(window.location.origin);
      // http://47.92.243.248
      axios({
        url:
          window.location.origin + "/prod-api/biz/invoice/preview/" + item.id,
        method: "GET",
        responseType: "blob", // 重要
      })
        .then((response) => {
          console.log(response.data);
          const blob = new Blob([response.data], { type: "application/pdf" });
          const url = URL.createObjectURL(blob);
          window.open(url);
        })
        .catch((error) => {
          console.error("Error downloading the file:", error);
        });
    },
    payInvoice(item) {
      console.log(item);
      this.form_payInvoice.payTime = "";
      this.open_payInvoice = true;
      
      this.form_payInvoice.id = item.id;
      this.form_payInvoice.payAmount = item.invoiceTaxAmount;
      this.form_payInvoice.remark = item.remark;
    },
    submitForm_payInvoice() {
      payInvoice({
        id: this.form_payInvoice.id,
        amount: this.form_payInvoice.payAmount,
        payTime: this.form_payInvoice.payTime,
        remark: this.form_payInvoice.remark,
      }).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("確認成功");
          this.cancel_payInvoice();
          this.getList();
        }
      });
    },
    cancel_payInvoice() {
      this.open_payInvoice = false;
    },
    /** 查询發票單列表 */
    getList() {
      this.loading = true;
      listInvoice(this.queryParams).then((response) => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        invoiceTitle: null,
        invocieCode: null,
        quoteId: null,
        quoteCode: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        invoiceAmount: null,
        invoiceTaxAmount: null,
        taxAmount: null,
        invoiceStatus: null,
        payTime: null,
        inBankId: null,
        inBankNo: null,
        inBankName: null,
        inBankAmount: null,
        validMonth: null,
        dueDate: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
      };
      this.bizInvoiceItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中數据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$router.push({ path: "/invoice/invoice/add" });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.$router.push({
        path: "/invoice/invoice/edit",
        query: { id: id, invoiceSource: row.invoiceSource },
      });
    },
    handleDetail(row) {
      this.reset();
      const id = row.id || this.ids;
      this.$router.push({
        path: "/invoice/invoice/detail",
        query: { id: id, invoiceSource: row.invoiceSource },
      });
    },
    // 撤回操作
    handleCancel(row) {
      const ids = row.id || this.ids;
      let that = this;
      this.$modal
        .confirm('是否確認撤回發票單編號為"' + ids + '"的數据项？')
        .then(function () {
          cancelInvoice({
            id: ids,
            amount: "",
            payTime: "",
            remark: "",
          }).then((response) => {
            if (response.code == 200) {
              that.$modal.msgSuccess("撤回成功");
              that.getList();
            }
          });
        })
        .catch(() => {});
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否確認删除發票單編號為"' + ids + '"的數据项？')
        .then(function () {
          return delInvoice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 發票明細序號 */
    rowBizInvoiceItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 發票明細添加按钮操作 */
    handleAddBizInvoiceItem() {
      let obj = {};
      obj.invoiceCode = "";
      obj.invoiceItem = "";
      obj.invoiceItemName = "";
      obj.invoiceItemType = "";
      obj.invoiceItemTypeName = "";
      obj.itemAmount = "";
      obj.taxAmount = "";
      obj.tax = "";
      obj.itemTaxAmount = "";
      obj.quantity = "";
      obj.uint = "";
      obj.unitPrice = "";
      obj.remark = "";
      this.bizInvoiceItemList.push(obj);
    },
    /** 發票明細删除按钮操作 */
    handleDeleteBizInvoiceItem() {
      if (this.checkedBizInvoiceItem.length == 0) {
        this.$modal.msgError("請先選擇要删除的發票明細數据");
      } else {
        const bizInvoiceItemList = this.bizInvoiceItemList;
        const checkedBizInvoiceItem = this.checkedBizInvoiceItem;
        this.bizInvoiceItemList = bizInvoiceItemList.filter(function (item) {
          return checkedBizInvoiceItem.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中數据 */
    handleBizInvoiceItemSelectionChange(selection) {
      this.checkedBizInvoiceItem = selection.map((item) => item.index);
    },
    /** 導出按钮操作 */
    handleExport() {
      this.download(
        "biz/invoice/export",
        {
          ...this.queryParams,
        },
        `invoice_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
